package com.gary.lockDemo;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 使用lock
 *  多线程编程步骤
 *      1、创建资源类
 *      2、创建线程，调用资源类
 * @author peng_rui
 * @date 2022/3/14
 */

class Ticket {
    private int count = 30;

    ReentrantLock lock = new ReentrantLock();

    public void sale() {
        //上锁
        lock.lock();
        try {
            if (count > 0) {
                System.out.println(Thread.currentThread().getName() + " : " + "卖出第" + (count--) + "张票" );
            }
        } finally {
            lock.unlock();
        }
    }
}
public class LSaleTicket {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }
        }, "AA").start();

        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }
        }, "BB").start();

        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }
        }, "CC").start();
    }
}
